package com.huazi.www.dept.util;

import java.sql.*;

/**
 * 数据库工具类
 */
public class BaoDao {
    public Connection conn = null;

    //链接
    public Connection connection() {
        //驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital?useUnicode=true&characterEncoding=utf8", "root", "123456");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //释放资源
    public void Colls(Connection conn, PreparedStatement preparedStatement, ResultSet resultSet) {
        try {
            if (conn != null) {
                conn.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //增删改
    public int excyteUpdate(String sql, Object... arr) {
        int num = 0;
        conn = connection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {
                preparedStatement.setObject(i + 1, arr[i]);
            }
            num = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Colls(conn, preparedStatement, null);
        }
        return num;
    }

    //查询
    public ResultSet executeQuery(String sql, Object... arr) {
        ResultSet rs = null;
        conn = connection();
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {
                preparedStatement.setObject(i + 1, arr[i]);
            }
            rs = preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

}
